package cn.kent.base.interrupt;

/**
 * interrupt方法和isInterrupt区别
 * <p>
 * 调用interrupted（）方法后中断标志被清除了。
 */
public class InterruptTest3 {
    public static void main(String[] args) throws InterruptedException {
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                for (; ; ) {

                }
            }
        });

        thread.start();
        // 设置中断标志
        thread.interrupt();
        // 获取中断标志
        System.out.println("isInterrupted1-> " + thread.isInterrupted());
        // 获取中断标志并重置
        System.out.println("isInterrupted2-> " + thread.interrupted()); // 为什么是false？ 因为是获取的当前线程，相当于Thread.interrupted()
        // 获取中断标志并重置
        System.out.println("isInterrupted3-> " + Thread.interrupted());
        // 获取中断标志
        System.out.println("isInterrupted4-> " + thread.isInterrupted());
        thread.join();
        System.out.println("main thread is over");
    }

    // //上面例子修改为下面例子
    // // 调用interrupted（）方法后中断标志被清除了。
    // public static void main(String[] args) throws InterruptedException {
    //     Thread thread = new Thread(() -> {
    //         System.out.println("thread isInterrupted:" + Thread.currentThread().isInterrupted());
    //         // 中断标志为true时，会退出循环，并且清除中断标志
    //         while (!Thread.currentThread().interrupted()) {
    //
    //         }
    //         System.out.println("thread isInterrupted:" + Thread.currentThread().isInterrupted());
    //     });
    //
    //     thread.start();
    //     // 设置中断标志
    //     thread.interrupt();
    //     thread.join();
    //     System.out.println("main thread is over");
    // }

}
